package com.lson.MQ.rabbit;

import com.lson.MQ.RabbitMqService;
import com.lson.MQ.rabbit.entity.Order;
import com.lson.MQ.rabbit.mapper.OrderMapper;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.UUID;

//@RestController
public class RabbitController {
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    OrderMapper orderMapper;

    @RequestMapping("/rabbit/sendMsg")
    public void sendMsg(String msg){
        Order order = new Order();
        order.setId(UUID.randomUUID().toString());
        order.setContent(msg);
        orderMapper.insert(order);
//        System.out.println(orderMapper);
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(order.getId());
        rabbitTemplate.convertAndSend(RabbitConfig.ORDER_EXCHANGE,RabbitConfig.ROUTING_KEY,order,correlationData);

    }

    @RabbitListener(queues = RabbitConfig.ORDER_QUEUE)
    @RabbitHandler
    public void processMessage2(Order order, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) {
        System.out.println(order);
        try {
            channel.basicAck(tag,false);            // 确认消息
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
